var util = require('../../utils/util.js');
var api = require('../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    remind: true,
    successImg: '',
    upLoadSuccess:'',
    checked: false,
    numBtnList: [],
    productNum: 0,
    numIndex: -1,
    selectInput: 0,
    con: '',
    checkedAddress: {},
    addressId: 0,
    totalPrice: 0,
    freight: 0,
    note: '',
    productInfo: {},
    isFirstClick: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let params = JSON.parse(options.obj);
    this.setData({
      successImg: params.successImg,
      productInfo: params.productInfo,
      id: params.id,
    });
    this.setSelectBtn();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let addressID = wx.getStorageSync('addressId');
    if (addressID !== '' && addressID !== undefined) {
      // 获取用户收货地址 显示默认那一条
      this.setData({
        addressId: addressID
      })
      // 有addressID 获取指定的收货地址
      this.getAddressInfo(addressID);
    }
    this.setData({
      isFirstClick: 0
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('addressId');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  checkboxChange(e) {
    let checked = e.currentTarget.dataset.checked;
    this.setData({
      checked: !checked
    });
  },
  confirm() {
    let checked = this.data.checked;
    if (checked) {
      this.setData({
        remind: false
      });
      this.upLoadImg();
    } else {
      wx.showToast({
        title: '请勾选协议',
        icon: 'none',
        duration: 2000
      });
    }
  },
  upLoadImg() {
    let that=this;
    let successImg=this.data.successImg;
    wx.uploadFile({
      url: 'https://function.duolaibei.com/admin/upload/serviceUp', //仅为示例，非真实的接口地址
      filePath: successImg,
      name: 'image',
      formData: {
        user: 'test'
      },
      success(res) {
        let list = JSON.parse(res.data);
        that.setData({
          upLoadSuccess:list.content
        });
      }
    });
  },
  // 返回上一级
  goBack() {
    wx.navigateBack();
  },
  // 设置商品可选数量列表
  setSelectBtn() {
    let minNum = this.data.productInfo.minNum,
      btnsList = [];
    for (let i = 1; i < 4; i++) {
      btnsList.push(minNum * i);
    };
    this.setData({
      numBtnList: btnsList
    });
  },
  // 选择商品件数
  selectProductNum(e) {
    this.setData({
      numIndex: e.currentTarget.dataset.index,
      productNum: e.currentTarget.dataset.num,
      selectInput: 0,
      con: ''
    });
    this.calcTotal();
  },
  // 输入框获取焦点
  startInputNum(e) {
    this.setData({
      selectInput: 1,
      numIndex: -1
    });
  },
  // 输入框失去焦点
  inputNum(e) {
    let productInfo = this.data.productInfo;
    let val = e.detail.value;
    if (Number(val) < productInfo.minNum) {
      wx.showToast({
        title: '不得小于起订数',
        icon: "none",
        duration: 2000
      });
      val = productInfo.minNum;
    }
    this.setData({
      productNum: val,
      con: val
    });
    this.calcTotal();
  },
  // 计算商品件数
  calcTotal() {
    let num = this.data.productNum;
    let productInfo = this.data.productInfo;
    this.setData({
      totalPrice: num * productInfo.price
    });
  },
  getAddressInfo(id) {
    let that = this;
    util.requestApi(api.getAddressInfo, {
      addressID: id
    }).then(function (res) {
      if (res.code == 200) {
        that.setData({
          checkedAddress: res.content
        })
      }
      // 计算运费
      wx.removeStorageSync('addressId');
    })
  },
  // 点击跳转去选择地址界面
  toSelectAddress: function () {
    wx.navigateTo({
      url: '/pages/ucenter/address/index?type=1',
    });
  },
  goIndex() {
    wx.redirectTo({
      url: '/pages/ucenter/diy-order-list/index',
    });
  },
  preImg() {
    var that = this;
    var src = that.data.successImg; //获取data-src
    var imgList = [that.data.successImg]; //获取data-list
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },
  createCustomOrder() {
    let that = this;
    let userId = wx.getStorageSync('userID'),shareID = wx.getStorageSync('uid');
    let productInfo = that.data.productInfo,
    upLoadSuccess = that.data.upLoadSuccess;
    if (that.data.isFirstClick !== 0) {
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否确认下单',
      success(res) {
        if (res.confirm) {
          that.setData({
            isFirstClick: 1
          });
          wx.showLoading({
            title: '生成订单中',
          });
          if (that.data.productNum == 0) {
            wx.hideLoading();
            that.setData({
              isFirstClick: 0
            });
            wx.showToast({
              title: '请选择商品数量',
              icon: 'none',
              duration: 2000
            });
            return;
          }
          if (that.data.addressId == 0) {
            wx.hideLoading();
            that.setData({
              isFirstClick: 0
            });
            wx.showToast({
              title: '请选择收货地址',
              icon: 'none',
              duration: 2000
            });
            return;
          }
          util.requestApi(api.createCustomOrder, {
            userID: userId,
            customID: that.data.id,
            addressID: that.data.addressId,
            comment: upLoadSuccess,
            count: that.data.productNum,
            money: that.data.totalPrice,
            postageMoney: 0,
            note: that.data.note,
            shareID:shareID?shareID:0
          }).then(function (res) {
            if (res.code == 200) {
              let con = res.content
              wx.requestPayment({
                timeStamp: con.timeStamp,
                nonceStr: con.nonceStr,
                package: con.package,
                signType: con.signType,
                paySign: con.paySign,
                success(res) {
                  wx.hideLoading();
                  wx.showModal({
                    title: '提示',
                    content: '下单成功，查看订单',
                    showCancel: false,
                    success(res) {
                      if (res.confirm) {
                        that.goIndex();
                      }
                    }
                  })
                },
                fail(res) {
                  wx.hideLoading();
                  that.setData({
                    isFirstClick: 0
                  });
                  wx.showToast({
                    title: '下单失败',
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            }
          });
        } else if (res.cancel) {
          that.setData({
            isFirstClick: 0
          });
        }
      }
    });
  },
  noteAreaBlur(e) {
    this.setData({
      note: e.detail.value
    });
  }
})